<template>
  <el-card class="message-item" shadow="never">
    <div class="message-header">
      <el-avatar size="small">{{ message.username.charAt(0) }}</el-avatar>
      <strong style="margin-left: 10px;">{{ message.username }}</strong>
      <span style="margin-left: auto; color: gray;">{{ message.updateTime }}</span>
    </div>
    <div class="message-content" style="margin: 10px 0;">
      {{ message.content }}
    </div>
    <div class="message-actions">
      <el-button type="text" size="mini" @click="replyVisible = !replyVisible">
        回复
      </el-button>
    </div>

    <!-- 回复输入 -->
    <div v-if="replyVisible" class="reply-input">
      <el-form ref="replyTextForm" :model="replyTextForm" :rules="replyTextRules">
        <el-form-item prop="replyText">
          <el-input
            type="textarea"
            v-model="replyTextForm.replyText"
            :rows="2"
            placeholder="请输入回复内容"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div style="text-align: right; margin-top: 5px;">
        <el-button type="primary" size="mini" @click="submitReply">发送</el-button>
        <el-button size="mini" @click="cancelReply">取消</el-button>
      </div>
    </div>

    <!-- 递归显示子留言 -->
    <div class="message-children">
      <message-item
        v-for="child in message.children"
        :key="child.id"
        :message="child"
        @reply="$emit('reply', ...arguments)"
        @refresh="onChildRefresh"
      />
    </div>
  </el-card>
</template>

<script>
import { publishMessage } from "@/api/message/message";
export default {
  name: 'MessageItem',
  props: {
    message: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      replyVisible: false,
      replyTextForm:{
        replyText: '',
      },
      replyTextRules: {
        replyText: [
          { required: true, trigger: "blur", message: "评论不能为空" },
          { min: 3, max: 200, message: "请输入评论（3~200字）", trigger: "blur" }
        ],
      },
    }
  },
  methods: {
    submitReply() {
      this.$refs.replyTextForm.validate(valid => {
        if (valid) {
          publishMessage(this.message.id, this.replyTextForm.replyText).then(res => {
            this.$emit('refresh')
          })
          this.replyTextForm.replyText = ''
          this.replyVisible = false
        }
      })
    },
    cancelReply() {
      this.replyTextForm.replyText = ''
      this.replyVisible = false
    },
    // 当子组件发起 refresh 时，继续往上冒泡
    onChildRefresh() {
      this.$emit('refresh')
    }
  }
}
</script>

<style scoped>
.message-item {
  margin: 10px 0;
}
.message-header {
  display: flex;
  align-items: center;
}
.message-children {
  margin-left: 20px;
  border-left: 1px dashed #ccc;
  padding-left: 10px;
}
</style>
